package org.geektimes.context;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;

public class ComponentContext {
    private static ServletContext servletContext;
    public static final String CONTEXT_NAME = ComponentContext.class.getName();
    private Context context;

    public static ComponentContext getInstance() {
        return (ComponentContext)servletContext.getAttribute(CONTEXT_NAME);
    }

    public void init(ServletContext servletContext) {
        try {
            context = (Context)new InitialContext().lookup("java:comp/env");
        } catch (NamingException e) {
            servletContext.log(e.getMessage(),e);
        }
        servletContext.setAttribute(CONTEXT_NAME,this);
        this.servletContext = servletContext;
    }

    public <C> C getComponent(String name) {
        C component=null;
        try {
            component = (C)context.lookup(name);
        } catch (NamingException e) {
            e.printStackTrace();
        }
        return component;
    }

    public void destroy() {
        if (context != null) {
            try {
                context.close();
            } catch (NamingException e) {
                e.printStackTrace();
            }
        }
    }
}
